<template>
  <vxe-grid
    ref="xGrid"
    v-bind="gridOptions"
    :header-cell-class-name="gridOptions.headerCellClassName"
    :row-class-name="gridOptions.rowClassName"
    :cell-class-name="gridOptions.cellClassName"
    stripe
    round
    v-on="gridEvents"
    @checkbox-change="selectChangeEvent"
    @checkbox-all="selectAllEvent"
  >
  </vxe-grid>
</template>

<script>
import { defineComponent, onMounted, reactive, ref } from "vue";
import { ElMessageBox } from "element-plus";

import { VXETable } from "vxe-table";
import XEUtils from "xe-utils";
import Bus from "./../../assets/Bus.ts";
import skFilterBar from "@/components/skFilterBar";
import "./plugins/formatter.js";
import "./plugins/table/index.js";
import api from "../../api";

// import "./plugins/index.ts"
VXETable.setConfig({
  size: "mini",
});

// VXETable.interceptor.add("event.reset", () => {
//   // 比如点击了某个组件的弹出层面板之后，此时被激活单元格不应该被自动关闭，通过返回 false 可以阻止默认的行为。
//   alert(1);
//   return false;
// });
export default defineComponent({
  components: { skFilterBar },
  props: {
    gridOps: {},
    gridEvts: {},
    url: {},
    tablecode: {
      type: String,
      default: () => "",
    },
    children: { type: Object, default: () => null },
    params: { type: Object, default: () => null },
  },
  setup(props) {
    const xGrid = ref({});

    const serveApiUrl = ref(props.url);
    let filterBarData = [];
    let searchData = [];
    const footerData = ref(null);

    const skFilterRef = ref({});
    const selectRecords = ref([]); //选择项
    const gridOptions = reactive({});
    const fieldUrl = api.system.table.info;

    const gridEvents = {
      headerCellClick(data) {
        Bus.emit("headerCellClick", data);
      },
      checkMethod(row) {
        Bus.emit("checkMethod", row);
        return true;
      },
      filterReset() {
        //清空数据
        skFilterRef.value.clear();
      },
      headerCellDblclick(data) {
        Bus.emit("headerCellDblclick", data);
      },
      headerCellMenu(data) {
        Bus.emit("headerCellMenu", data);
      },
      cellClick(data) {
        Bus.emit("cellClick", data);
      },
      cellDblclick(data) {
        Bus.emit("cellDblclick", data);
      },
      cellMenu(data) {
        Bus.emit("cellMenu", data);
      },
      footerCellClick(data) {
        Bus.emit("footerCellClick", data);
      },
      footerCellDblclick(data) {
        Bus.emit("footerCellDblclick", data);
      },
      footerCellMenu(data) {
        Bus.emit("footerCellMenu", data);
      },

      //返回上一个结果集的交集，差集
      selectData(data) {
        Bus.emit("selectData", data);
      },
      scroll(data) {
        Bus.emit("scroll", data);
      },
      zoom(data) {
        Bus.emit("zoom", data);
      },

      editRow: param => {
        let Records = param.$grid.getCheckboxRecords();
        for (let i in Records) param.$grid.setEditRow(Records[i]);
      },
      //重新新增一行方法
      addRow: param => {
        // if (typeof gridOptions.data == "undefined")
        //   gridOptions.data = [];
        var clm = {};
        gridOptions.columns.forEach(v => {
          if (v.field != "id") {
            XEUtils.set(clm, v.field, v.defaultValue);
          }
        });

        param.$grid.insert(clm).then(data => {
          param.$grid.setEditRow(data.row);
          // gridOptions.data.push(data.row);
        });
      },
      removeRow: async param => {
        const type = await ElMessageBox.confirm("您确定要删除该数据?");
        if (type === "confirm") {
          return param.$grid.removeCheckboxRow();
        }
      },
    };

    //查询后保存参数

    const mergeOptions = {
      border: true,
      showFooter: false,
      tablecode: "",
      showOverflow: true,
      just_fetch_field: false,
      loading: false,
      mouseConfig: {
        selected: true,
      },
      //会把初始化数据清空了
      height: 300,
      // data: [],
      footerMethod: function (dataGrid) {
        if (footerData.value) {
          return footerData.value;
        }
        var footer1 = [];
        var footer2 = [];
        var hasfoot2 = true;
        var digits = 2,
          hiddenColCount = 0;
        if (dataGrid.data.length == 0) return;

        if (typeof dataGrid.$grid.footsum == "undefined") hasfoot2 = false;
        for (var col in dataGrid.$grid.props.columns) {
          //隐藏的列数
          if (dataGrid.$grid.props.columns[col].visible === false) hiddenColCount++;

          if (dataGrid.$grid.props.columns[col].sum) {
            var field = dataGrid.$grid.props.columns[col].field;

            footer1[col - hiddenColCount] = XEUtils.toFixed(
              XEUtils.sum(dataGrid.data, field),
              digits
            );
            if (hasfoot2)
              footer2[col - hiddenColCount] = XEUtils.toFixed(
                XEUtils.toNumber(dataGrid.$grid.footsum[field]),
                digits
              );
          } else {
            footer1[col - hiddenColCount] = null;
            if (hasfoot2) footer2[col - hiddenColCount] = null;
          }
        }

        if (!hasfoot2) return [footer1];
        else return [footer1, footer2];
      },

      keepSource: true,
      id: "full_edit_1",

      rowConfig: {
        keyField: "id",
        isHover: true,
        height: 31,
        useKey: "id",
      },
      columnConfig: {
        resizable: true,
        useKey: "id",
      },

      sortConfig: {
        trigger: "cell",
        remote: true,
      },
      filterConfig: {
        remote: true,
      },

      proxyConfig: {
        seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
        sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
        filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
        form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
        message: false,
        // 对应响应结果 { result: [], page: { total: 100 } }
        props: {
          result: "rows", // 配置响应结果列表字段
          total: "total", // 配置响应结果总页数字段
        },

        // 只接收Promise，具体实现自由发挥
        ajax: {
          // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
          query: ({ page, sorts, filters, form, $grid }) => {
            const queryParams = Object.assign({}, form);

            const firstSort = sorts[0];
            if (firstSort) {
              queryParams.sort = firstSort.property;
              queryParams.order = firstSort.order;
            }
            // if (filters) {
            queryParams["filter"] = [];
            // }
            // 处理筛选条件
            filters.forEach(data => {
              let filter = data.datas[0];
              let field = "";
              //select 筛选 值和内容可能不一样
              if (filter.filterfield != null && filter.filterfield != "")
                field = filter.filterfield;
              else field = data.property;
              queryParams["filter"].push({
                [field]: data.datas[0],
              });
            });

            filterBarData.forEach(data => {
              queryParams["filter"].push(data);
            });

            searchData.forEach(data => {
              queryParams["filter"].push(data);
            });
            if (props.params != null) {
              queryParams["filter"].push(props.params);
            }

            queryParams["page"] = page.currentPage;
            queryParams["pageSize"] = page.pageSize;
            let sumparam = [];

            Object.values($grid.props.columns).forEach(function (k) {
              if (k.sum) {
                sumparam[sumparam.length] = k.field;
              }
            });

            if (gridOptions.footerRowCount == 2) {
              if (sumparam.length > 0) queryParams["sums"] = sumparam;
            }
            return serveApiUrl.value.post(queryParams).then(function (res) {
              $grid.footsum = res.data.sums;
              footerData.value = res.data.footer ?? null;
              return {
                rows: res.data.rows ?? res.data,
                total: res.data.total ?? 0,
              };
            });
          },
        },
      },

      checkboxConfig: {
        // labelField: "id",

        highlight: true,

        //父子不关联，树
        checkStrictly: false,
        trigger: "row",
        resizable: true,
        //保留勾选
        reserve: true,
        //通过鼠标在复选框的列内滑动选中或取消指定行
        range: true,
        checkMethod({ row }) {
          return gridEvents.checkMethod(row);
        },
      },

      editConfig: {
        trigger: "click",
        mode: "row",
        // autoClear: false,
        showIcon: false,
        showStatus: true,
      },

      set columns(val) {
        val.forEach((v, k) => {
          if (["seq", "checkbox", "radio", "expand", "html"].indexOf(v.type) === -1) {
            if (v.filterable == true) {
              v["xtype"] = v.type;
              v["filters"] = [
                {
                  data: {
                    type: v.type == "number" ? "eq" : "lk",
                    xtype: v.type,
                    value: "",
                    filterfield: v.filterfield,
                  },
                },
              ];
              val[k]["filterRender"] = {
                name: "FilterNew",
                attrs: v,
              };
            }
            //子表不可编辑
            // if (v.editable == true) {
            //   v["xtype"] = v.type;
            //   val[k]["editRender"] = { name: "EditRender", attrs: v, autofocus: "input" };
            // }
            if (v.type == "CellRender" && v.editable != true) {
              // v.type = "html";
              val[k]["cellRender"] = {
                name: v.formatter,
                attrs: v,
              };
              delete val[k].formatter;
            }
            delete val[k].type;
          }
        });

        if (this.vcolumns) {
          val.forEach(v => {
            this.vcolumns.some((vv, kk) => {
              if (v.field == vv.field) {
                if (vv.editRender == true && typeof v.event != "undefined") {
                  this.vcolumns[kk]["EditRender"]["event"] = v.event;
                }
                Object.assign(this.vcolumns[kk], v);
                return true;
              }
            });
          });
        } else {
          this.vcolumns = val;
        }
      },
      get columns() {
        return [{ visible: false }, ...this.vcolumns];
      },
    };

    onMounted(async () => {
      Object.assign(
        mergeOptions,
        await getRemoteOption(
          fieldUrl,
          typeof props.gridOps == "undefined" ||
            typeof props.gridOps.tablecode == "undefined"
            ? typeof props.tablecode == "undefined"
              ? ""
              : props.tablecode
            : ""
        ),
        props.gridOps
      );

      Object.assign(gridOptions, mergeOptions);

      Object.assign(gridEvents, props.gridEvts);
      //树形
      let seqWith = 35;

      // else delete gridOptions.columns[1];
      if (gridOptions.showColumnNum)
        gridOptions.columns[0] = { type: "seq", width: seqWith };
      // else delete gridOptions.columns[0];

      // Bus.on("cellDblclick", function (data) {
      //   router.push({ path: "./save", data });
      // });
    });
    //设置筛选
    function scFilterBarchange(data) {
      const $grid = xGrid.value;
      filterBarData = data;
      $grid.commitProxy("query");
    }

    //简单的包含搜索
    function search(field, value, type) {
      searchData.forEach(function (v, k) {
        if (typeof v[field] != "undefined") delete searchData[k];
      });
      searchData[searchData.length] = {
        [field]: { value: value, type: type },
      };
    }
    async function getRemoteOption(url, param) {
      if (param != "") {
        var data = await url.get({ code: param });
        data.data.id = data.data.code;
        delete data.data.toolbarConfig;
        return data.data;
      }
      return {};
    }
    const selectChangeEvent = ({ records }) => {
      selectRecords.value = records;
    };
    const selectAllEvent = param => {
      selectChangeEvent(param);
    };

    return {
      xGrid,
      gridOptions,
      gridEvents,
      scFilterBarchange,
      filterBarData,
      search,
      selectChangeEvent,
      selectAllEvent,
    };
  },
});
</script>

<style>
.vxe-export--panel tbody tr:last-of-type {
  display: none;
}

.vxe-export--panel-column-body li:nth-child(-n + 3) {
  display: none;
}

.vxe-body--expanded-row {
  background-color: #f5f4f4;
}

.vxe-body--expanded-row .vxe-body--expanded-cell {
  margin-left: 35px;
  border: 1px solid #ccc;
  background-color: #f6f6f6;
}
</style>
